package server.auction;

/**
 * This class sends notifications to a client via udp and
 * Datagram-packets.
 *
 * @version 1.0 vom 19.10.2012
 * @author Peter Tillian 1026312
 */

import java.net.InetAddress;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.DatagramPacket;
import java.io.IOException;

import model.*;

public class AuctionServerNotificationThread extends Thread {
	private int udpPort;
	private InetAddress address;
	private DatagramSocket socket = null;
	private User loggedInUser;

	public AuctionServerNotificationThread(int udpPort, InetAddress address,
			User loggedInUser) {
		super("ServerNotificationThread");
		this.udpPort = udpPort;
		this.address = address;
		this.loggedInUser = loggedInUser;

		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			System.err.println("Error creating DatagramSocket in "
					+ this.getClass() + ": " + e.getMessage());
		}
	}

	public void run() {
		do { // the first time this thread starts, try to send old
				// notifications!
			if (this.loggedInUser.isLoggedIn()) {
				synchronized (this.loggedInUser) {
					for (String notification : this.loggedInUser
							.getNotifications()) {
						byte[] buf = new byte[256];
						buf = notification.getBytes();
						DatagramPacket packet = new DatagramPacket(buf,
								buf.length, address, udpPort);

						try {
							socket.send(packet);
						} catch (IOException e) {
							System.err
									.println("Error sending udp-notification to client: "
											+ e.getMessage());
							socket.close();
							break;
						}
					}
					this.loggedInUser.getNotifications().clear();
				}
			}
			// if this thread is interrupted while not in a blocked-state.
			if (this.isInterrupted()) {
				this.interrupt();
			}

			// waiten for user-object to send new notifications.
			try {
				synchronized (this.loggedInUser) {
					this.loggedInUser.wait();
				}
			} catch (InterruptedException e) {
				if (!this.socket.isClosed()) {
					System.err.println("Interrupted while waiting "
							+ this.getClass() + ": " + e.getMessage());
				} else
					break;
			}
		} while (true);
	} // end run()

	@Override
	public void interrupt() {
		this.socket.close();
		super.interrupt();
	}
} // end of class ServerNotificationThread